import AiImage
import AiBlob
import AiBook
import os
from opencv import cv
from opencv import highgui
from xml.dom.minidom import parse, parseString

import sys
sys.path.append("../reasoning")
import AiReasoning

img = AiImage.AiImage("../../books/TheBraveMonkeyPirate/tbmp02.png")

## print img.blobs[0].parentImg.filename


book = AiBook.AiBook("../../books/TheBraveMonkeyPirate/TheBraveMonkeyPirate.xml")
book.findBlobs()

#for page in book.pages:
#    page.findBlobs()
#    AiImage.showAiImage(page.blobimage)
blobs = []
theta = 0.8
for p in book.pages:
	blobs.extend(p.blobs)
print len(blobs)
(wrel, blobrel) = AiReasoning.build_relations([], blobs)
groups = AiReasoning.group_2(list(blobs), blobrel, theta)

print groups

groups.sort()

i = 0
for group in groups:
	os.mkdir("../../test/group"+str(i))
	j = 0
	print "Group", i
	for blob in group:
		highgui.cvSaveImage("../../test/group"+str(i)+"/"+str(j)+".png",blob.image)
		print "\t",blob.id
		j+=1
	i+=1
'''print len(book.pages[2].blobs)
#blobs = book.pages[2].blobs
#blob = AiBlob(None,None,book.pages[2].image.img, None)
#blobs[0].image=blobs[0].parentImg.img
for i in range(len(blobs)-1):
    for j in range(len(blobs)-1):
        highgui.cvNamedWindow("win1")
        highgui.cvShowImage("win1",blobs[j].image)

        im = cv.cvCloneImage(blobs[i].image)
        cv.cvDrawContours(im, blobs[i].getShape(), cv.CV_RGB(255,1,1) ,cv.CV_RGB(1,1,255), 0,2)
        highgui.cvNamedWindow("win2")
        highgui.cvShowImage("win2",im)
#    print (AiBlob.compareBlobs(blobs[0],blobs[i]))
        print AiBlob.compShape(blobs[j],blobs[i])
        highgui.cvWaitKey(0)
'''
